package com.yc.controller;


import com.yc.FileDeduplicationService;
import com.yc.utils.FileTypeValidator;
import com.yc.web.bean.ResponseResult;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@RestController   // restful风格:    请求的method类型: get, post, put, delete,patch     返回值类型:json
@Log
public class FileUploadController {
    @Autowired
    private FileDeduplicationService fileDeduplicationService;

    @RequestMapping(  value="/upload",method = RequestMethod.POST )
    public ResponseResult upload(
            @RequestPart("uploadFiles")MultipartFile[] uploadFiles
    ){
        if (uploadFiles.length==0) {
            return ResponseResult.builder().code(0).msg("上传文件不能为空").build();
        }
        List<String> urls=new ArrayList<>();
        for(   MultipartFile file: uploadFiles){
            if( file.isEmpty() ){
                continue;
            }
            String contentType = file.getContentType();
            String originalFilename=file.getOriginalFilename();  //文件名
            if (!FileTypeValidator.isValidFileType(contentType, originalFilename)) {
                return  ResponseResult.builder().code(0).msg("文件类型不被允许: " + originalFilename + ". 只允许图片、PDF、Word、Excel格式。").build();
            }
            try {
                // Delegate file processing and deduplication to the service
                String fileUrl = fileDeduplicationService.processAndGetFileUrl(file);
                urls.add(fileUrl);
            } catch (Exception e) {
                e.printStackTrace();
                log.severe("上传文件到OSS失败: " + originalFilename);
            }
        }
        if(   urls.size()>0) {
            log.info("上传到OSS成功,多个图片的访问地址为:" + urls);
            return ResponseResult.builder().code(1).msg("上传接收数据成功").data(urls).build();
        }else{
            return ResponseResult.builder().code(0).msg("上传文件失败").build();
        }
    }
}
